import logging
import os
from datetime import datetime

# 日志配置
LOG_DIR = "logs"
LOG_LEVEL = logging.INFO


def ensure_log_dir_exists():
    """确保日志目录存在"""
    if not os.path.exists(LOG_DIR):
        os.makedirs(LOG_DIR)


def setup_logger(name: str = "app") -> logging.Logger:
    """设置日志记录器"""
    # 确保日志目录存在
    ensure_log_dir_exists()
    
    # 创建Logger
    logger = logging.getLogger(name)
    logger.setLevel(LOG_LEVEL)
    
    # 避免重复添加处理器
    if not logger.handlers:
        # 创建控制台处理器
        console_handler = logging.StreamHandler()
        console_handler.setLevel(LOG_LEVEL)
        
        # 创建文件处理器
        today = datetime.now().strftime("%Y-%m-%d")
        log_file = os.path.join(LOG_DIR, f"{name}_{today}.log")
        file_handler = logging.FileHandler(log_file)
        file_handler.setLevel(LOG_LEVEL)
        
        # 定义日志格式
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
        )
        
        # 添加格式化器到处理器
        console_handler.setFormatter(formatter)
        file_handler.setFormatter(formatter)
        
        # 添加处理器到Logger
        logger.addHandler(console_handler)
        logger.addHandler(file_handler)
    
    return logger


def get_logger(name: str = "app") -> logging.Logger:
    """获取日志记录器，如果不存在则创建"""
    logger = logging.getLogger(name)
    if not logger.handlers:
        logger = setup_logger(name)
    return logger